<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽</title>
    <style>
        .item {
            width: 100px;
            height: 100px;
            background-color: blue;
            position: absolute;
            left: 0;
            top: 0;
        }
    </style>
</head>

<body>
    <div class="item"></div>
    <script>
        let item = document.querySelector(".item");
        item.onmousedown = (e) => {
            let ox = e.offsetX;
            let oy = e.offsetY;
            document.onmousemove = (e) => {
                const minL = 0, maxL = innerWidth - 100, minT = 0, maxT = innerHeight - 100;
                let cx = e.clientX;
                let cy = e.clientY;
                let movX = cx - ox;
                let movY = cy - oy;
                item.style.left = movX + "px";
                item.style.top = movY + "px";
                if (movX < minL) {
                    item.style.left = minL + "px";
                } 
                if (movX > maxL) {
                    item.style.left = maxL + "px";
                } 
                if (movY < minT) {
                    item.style.top = minT + "px";
                }
                if (movY > maxT) {
                    item.style.top = maxT + "px";
                }
                // if (cx - ox < 0) {
                //     item.style.left = 0 + "px";
                // } else if (cx - ox + 100 >= innerWidth) {
                //     item.style.left = innerWidth - 100 + "px";
                // }
                // if (cy - oy < 0) {
                //     item.style.top = 0 + "px";
                // } else if (cy - oy + 100 >= innerHeight) {
                //     item.style.top = innerHeight - 100 + "px";
                // }
            }
            item.onmouseup = () => {
                document.onmousemove = null;
            }
        }

    </script>
</body>

</html>